package com.sjn.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <company> 上海瑞而克信息科技有限公司
 *
 * @author lke-bai
 * @date 2020/7/22 14:27
 * <description>
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        log.info("权限认证");
//
//
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpResponse response = exchange.getResponse();
//
//        String token = request.getHeaders().getFirst("Authorization");
//        String path = request.getURI().getPath();
//
//        log.info("#######请求地址：" + path);
//        log.info("#######token：" + token);
//
//
//        // 封装错误信息
//        Map<String, Object> responseData = Maps.newHashMap();
//        responseData.put("code", 401);
//        responseData.put("message", "非法请求");
//        responseData.put("cause", "Token is empty");
//
//        // 请求不为认证接口
//        if (path.indexOf("/auth2/oauth/") != 0) {
//            // 没有token拒绝访问
//            if (StringUtils.isEmpty(token)) {
//                try {
//                    // 将信息转换为 JSON
//                    ObjectMapper objectMapper = new ObjectMapper();
//                    byte[] data = objectMapper.writeValueAsBytes(responseData);
//
//                    // 输出错误信息到页面
//                    DataBuffer buffer = response.bufferFactory().wrap(data);
//                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                    response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//                    return response.writeWith(Mono.just(buffer));
//
//                } catch (JsonProcessingException e) {
//                    log.error(e.getMessage());
//                    e.printStackTrace();
//                }
//            } else {
//                // 验证token
////                JSONObject object = feignService.oauthUser(token, "");
//
////                HashMap<String, Object> map = new HashMap<>();
////                map.put("userID","25453");
////                JSONObject object = feignService.oauthUser(map);
////                object.get("");
//                return sginLog(exchange, chain);
//            }
//        }
//        return sginLog(exchange, chain);

        return chain.filter(exchange);
    }

    /**
     * 设置过滤器的执行顺序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}


